import urllib.request
import json
import jsonpath

# 请求部分
url = "https://www.taopiaopiao.com/cityAction.json?activityId&_ksTS=1727611110572_105&jsoncallback=jsonp106&action=cityAction&n_s=new&event_submit_doGetAllRegion=true"
headers = {  # 注意字典键名应为 'headers' 而不是 'headrs'
    "referer": "https://www.taopiaopiao.com/?",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"
}
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")

# 处理 JSONP 格式的数据
content = html.split("(", 1)[1].rsplit(")", 1)[0]

# 将数据写入文件
with open("city.json", "w", encoding="utf-8") as fp:
    fp.write(content)
    print("写入成功")

# 读取并解析 JSON 文件
with open("city.json", "r", encoding="utf-8") as file:
    obj = json.load(file)

# 使用 jsonpath 提取数据
city_list = jsonpath.jsonpath(obj, "$..regionName")
print(city_list)

